package com.cskaoyan.market.filter;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName AuthenticateFilter
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/5/10 9:38
 * @Version V1.0
 **/
//@WebFilter("/admin/*")
@WebFilter("/*")
public class AuthenticateFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // /admin/auth/login  /admin/auth/logout不需认证，其他接口需要进行认证
        //如果是除了上述这两个地址之外的请求地址，那么全部需要进行认证，也就是仅登录之后才可以访问
        HttpServletRequest request= (HttpServletRequest) req;
        //当前的请求资源路径
        String requestURI = request.getRequestURI();
        if(requestURI.equals(request.getContextPath() + "/admin/auth/login") || requestURI.equals(request.getContextPath() + "/admin/auth/logout")){
            //只要是上述中任何一个地址，那么放行
            System.out.println("登录放行");
            chain.doFilter(request, resp);
            return;
        }
        //如果不是上述两个中的任意一个路径，那么需要进行认证，判断是否登录
        HttpSession session = request.getSession();
        Object admin = session.getAttribute("admin");
        if(admin == null){
            //没有登录
            System.out.println("没有登录");
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.unlogin()));
            return;
        }
        //登录
        System.out.println("认证成功" + admin);
        chain.doFilter(request, resp);
    }

    @Override
    public void destroy() {

    }
}
